﻿using System;
using System.Collections.Generic;

namespace _5E.Utils.DbHelper.EasySQL.Creator
{
    /// <summary>
    /// 程序说明：创建EasySQL基类
    /// 创建作者：ahl
    /// 创建时间：2012-04-16
    /// </summary>
    public abstract class BaseCreator
    {
        #region 变量

        private const string INVALID_PROPERTY_ERROR_MESSAGE_FORMAT = "无效属性:{1}";

        private const string COLUMN_SEPARATOR = ", ";

        #endregion

        #region 实例属性

        private string m_TableName = null;
        public string TableName { get { return this.m_TableName; } }

        private Dictionary<string, string> m_AllColumns = null;
        protected Dictionary<string, string> AllColumns { get { return this.m_AllColumns; } }

        #endregion

        #region 构造函数

        private BaseCreator() { }

        public BaseCreator(string tableName, Dictionary<string, string> allColumns)
        {
            this.m_TableName = tableName;
            this.m_AllColumns = allColumns;
        }

        #endregion

        #region 实例方法

        public string Create()
        {
            var sql = this.CreateSQL();
            this.Reset();
            return sql;
        }

        protected abstract string CreateSQL();

        protected abstract void Reset();

        protected string GetColumnName(string propertyName)
        {
            string columnName = GetColumnName(propertyName, this.AllColumns);
            return columnName;
        }

        #endregion

        #region 静态方法

        public static string GetColumnName(string propertyName, Dictionary<string, string> allColumns)
        {
            string columnName;
            var invalidPropertyName = !allColumns.TryGetValue(propertyName, out columnName);
            if (invalidPropertyName)
            {
                var errorMessage = string.Format(INVALID_PROPERTY_ERROR_MESSAGE_FORMAT, propertyName);
                throw new ArgumentOutOfRangeException(errorMessage);
            }
            return columnName;
        }

        public static string ToColumnString(string[] columns)
        {
            var columnString = string.Join(COLUMN_SEPARATOR, columns);
            return columnString;
        }

        #endregion
    }
}
